package com.yanqu.road.dao.impl.message;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.messageSubscribe.entity.ChannelTemplateInfo;
import com.yanqu.road.entity.messageSubscribe.entity.MessageSubscribeInfo;
import com.yanqu.road.entity.messageSubscribe.entity.MessageSubscribePlayerData;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MessageSubscribeDaoImpl extends TempDataObjectDao<MessageSubscribePlayerData> {

    public Map<String, ChannelTemplateInfo> getChannelTemplateMap(int channelId) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<String, ChannelTemplateInfo> dataMap = new ConcurrentHashMap<>();
        String sql = "select * from t_s_wechat_template WHERE channelId = ?";
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, channelId);
            rs = call.executeQuery();

            while (rs.next()) {
                ChannelTemplateInfo data = new ChannelTemplateInfo();
                data.setChannelId(rs.getInt("channelId"));
                data.setTemplateId(rs.getString("templateId"));
                data.setName(rs.getString("name"));
                data.setPushRateUnit(rs.getInt("pushRateUnit"));
                dataMap.put(data.getTemplateId(),data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public Map<Long, MessageSubscribePlayerData> getMessageSubscribeMap() {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Long, MessageSubscribePlayerData> dataMap = new ConcurrentHashMap<>();
        String sql = "select * from t_u_message_subscribe";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                MessageSubscribePlayerData data = parse(rs);
                dataMap.put(data.getPlayerId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    @Override
    protected boolean addData(MessageSubscribePlayerData data) {
        PreparedStatement call = null;
        String sql = "insert into t_u_message_subscribe(userId,openId,isSwitch,subscribeInfo,offLineTime,appExt) values (?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setLong(i++, data.getPlayerId());
            call.setString(i++, data.getOpenId());
            call.setBoolean(i++, data.isSwitch());
            call.setString(i++, JSON.toJSONString(data.getSubscribedMap()));
            call.setLong(i++, data.getOffLineTime());
            call.setString(i++, data.getAppExt());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean updateData(MessageSubscribePlayerData data) {
        PreparedStatement call = null;
        String sql = "update t_u_message_subscribe set openId=?,isSwitch=?,subscribeInfo=?,offLineTime=?,appExt=? where userId=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, data.getOpenId());
            call.setBoolean(i++, data.isSwitch());
            call.setString(i++, JSON.toJSONString(data.getSubscribedMap()));
            call.setLong(i++, data.getOffLineTime());
            call.setString(i++, data.getAppExt());
            call.setLong(i++, data.getPlayerId());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected MessageSubscribePlayerData parseData(ResultSet rs) throws SQLException {
        MessageSubscribePlayerData data = new MessageSubscribePlayerData();
        data.setPlayerId(rs.getLong("userId"));
        data.setOffLineTime(rs.getLong("offLineTime"));
        data.setOpenId(rs.getString("openId"));
        data.setIsSwitch(rs.getBoolean("isSwitch"));
        String appExt = rs.getString("appExt");
        if (appExt != null) {
            data.setAppExt(appExt);
        }
        String str = rs.getString("subscribeInfo");
        if (StringUtils.isNullOrEmpty(str)) {
            data.setSubscribedMap(new ConcurrentHashMap<>());
        }else {
            data.setSubscribedMap(JSON.parseObject(str, new TypeReference<ConcurrentHashMap<String, MessageSubscribeInfo>>() {
            }));
        }
        return data;
    }
}
